package com.ifcar.app.activity;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ifcar.app.adapter.HistorySearchAdapter;
import com.ifcar.app.adapter.SearchResultAdapter;
import com.ifcar.app.rss.GetColumnsInfo;
import com.ifcar.app.util.FileUtils;
import com.ifcar.app.util.ThemeSettingsHelper;
import com.ifcar.app.util.Tools;
import com.ifcar.app.view.SearchListView;
import com.ifcar.app.activity.R;

public class SearchNewsActivity extends BaseActivity {
	
	private static final String SEARCH_HISTORY_FIlE_TAG = "search_history_word_tag_file";
	private final int MAXHISTORY = 10;
	private final int MAXSUGGESTNUM = 10;
	
	private EditText mNewsSearchEditText;
	private Button mNewsSearchSubmit;
	private ImageView mClearSearchWord;
	
	private SearchListView mSearchListView;
	
	private AsyncTask<String, Void, List<Map<String, Object>>> mSearchTask;
	private ThemeSettingsHelper themeSettingsHelper;
	
	private InputMethodManager mInputMethodManager;
	private LinearLayout search_loadingbar; 
	
	/**
	 * 是否为提交搜索类型，区别搜索建议
	 */
	private boolean mIsSubmitSearch;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.search_news);
		themeSettingsHelper = getThemeSettingsHelper();
		
		hideIcon();
		initView();
		
		mNewsSearchEditText.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				// TODO Auto-generated method stub
				if(TextUtils.isEmpty(s)){
					mClearSearchWord.setVisibility(View.INVISIBLE);
					mNewsSearchSubmit.setEnabled(false);
					setSearchHistoryData();
				}else{
					findViewById(R.id.clear_search_word).setVisibility(View.VISIBLE);
					mNewsSearchSubmit.setEnabled(true);
//					if(Tools.isWifi(SearchNewsActivity.this)){
//						mIsSubmitSearch = false;
//						Editable keyword = mNewsSearchEditText.getText();
//						searchNewsTask(String.valueOf(keyword));
//					}
				}
				
			}
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}
			@Override
			public void afterTextChanged(Editable s) {
			}
		});
		
		mNewsSearchSubmit.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(null != mInputMethodManager){
					mInputMethodManager.hideSoftInputFromWindow(mNewsSearchEditText.getWindowToken(), 0);
				}
				
				Editable keyword = mNewsSearchEditText.getText();
				String searchWord = String.valueOf(keyword).trim();
				
				if(TextUtils.isEmpty(searchWord)){
					Toast.makeText(SearchNewsActivity.this, getString(R.string.search_invalid), Toast.LENGTH_SHORT).show();
					mNewsSearchEditText.setText("");
					return;
				}
				
				if(Tools.CheckNetwork(SearchNewsActivity.this)){
					mIsSubmitSearch = true;
					search_loadingbar.setVisibility(View.VISIBLE);
					searchNewsTask(String.valueOf(searchWord));
				}else{
					mSearchListView.setNetworkInvalid();
				}
			}
		});
		
		// 搜索结果 item click
		mSearchListView.getSearchResultListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				Map<String, Object> map = (Map<String, Object>) parent.getAdapter().getItem(position);
				String docid = (String) map.get(GetColumnsInfo.DOCID_TAG);
				String title = (String) map.get(GetColumnsInfo.TITLE_TAG);
				
				Intent intent = new Intent(SearchNewsActivity.this, NewsPage.class);
				Bundle b = new Bundle();
				b.putString(GetColumnsInfo.DOCID_TAG, docid);
				b.putString(GetColumnsInfo.TITLE_TAG, title);
				b.putString("push", "search");
				b.putString("position", "0");
				
				intent.putExtras(b);
				
				startActivity(intent);
			}
		});
		
		// 搜索历史或者建议 item click
		mSearchListView.getSearchHistoryListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
			
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				String suggest = (String) parent.getAdapter().getItem(position);
				mNewsSearchEditText.setText(suggest);
				mNewsSearchSubmit.performClick();
			}
		});
		
	}
	
	/**
	 * 搜索新闻
	 * @param valueOf
	 */
	protected void searchNewsTask(final String keyword) {
		// TODO Auto-generated method stub
		
		if(null != mSearchTask){
			mSearchTask.cancel(true);
			mSearchTask = null;
		}
		
		mSearchTask = new AsyncTask<String, Void, List<Map<String,Object>>>(){

			@Override
			protected List<Map<String, Object>> doInBackground(String... params) {
				// TODO Auto-generated method stub
				String keyword = params[0];
				
				List<Map<String, Object>> list = GetColumnsInfo.getSearchNewsData(SearchNewsActivity.this, keyword);
				
				if(mIsSubmitSearch){ // 更新搜索历史
					
					updateSearchHistory(keyword);
				}
				return list;
			}
			
			@Override
			protected void onPostExecute(List<Map<String, Object>> result) {
				// TODO Auto-generated method stub
				super.onPostExecute(result);
				handler.sendEmptyMessage(0);
				if(mIsSubmitSearch){ // 点击搜索
					if(result.size() > 0){
						SearchResultAdapter adapter = new SearchResultAdapter(SearchNewsActivity.this, themeSettingsHelper, result);
						mSearchListView.setSearchResultListViewAdapter(adapter);
					}else{
						mSearchListView.setNoResult4Search(keyword);
					}
				}else{ // 搜索建议
					if(result.size() > 0){ // 有搜索建议
						List<String> list = new ArrayList<String>();
						int len = result.size();
						len = len > MAXSUGGESTNUM ? MAXSUGGESTNUM : len;
						for(int i = 0; i < len; i ++){
							list.add((String) result.get(i).get(GetColumnsInfo.TITLE_TAG));
						}
						
						HistorySearchAdapter adapter = new HistorySearchAdapter(SearchNewsActivity.this, themeSettingsHelper, list);
						mSearchListView.setHistoryOrSuggestListViewAdapter(adapter);
					}else{ // 搜索历史或者之前搜索数据
						if(mSearchListView.isSearchAdapterNULL()){
							setSearchHistoryData();
						}else{
							mSearchListView.showSearchResultView();
						}
					}
				}
			}
		}.execute(keyword);
		
	}

	protected void updateSearchHistory(String keyword) {
		// TODO Auto-generated method stub
		List<String> list = FileUtils.readSearchHistoryData(SEARCH_HISTORY_FIlE_TAG);
		if(null == list){
			list = new ArrayList<String>();
		}
		
		int len = list.size();
		List<String> result = new ArrayList<String>();
		result.add(keyword);
		
		for(int i = 0; i < len; i ++){
			result.add(list.get(i));
		}
		
		int rLen = result.size();
		for(int i = 0; i < rLen; i ++){
			String history = result.get(i);
			
			if(history.equals(keyword) && i > 0){
				result.remove(i);
				rLen --;
			}
		}
		rLen = result.size();
		if(rLen > MAXHISTORY){
			for(int i = MAXHISTORY; i < rLen; i ++){
				result.remove(MAXHISTORY);
			}
		}
		
		FileUtils.writeSearchHistoryToLocal(result, SEARCH_HISTORY_FIlE_TAG, this);
	}
	
	private void initView() {
		// TODO Auto-generated method stub
	    
	    search_loadingbar = (LinearLayout)findViewById(R.id.search_loadingbar);
	    
		((TextView)findViewById(R.id.top_main_text)).setText(R.string.menu_news_search);
		
		mNewsSearchEditText = (EditText)findViewById(R.id.news_search_edit);
		mNewsSearchSubmit = (Button)findViewById(R.id.search_submit_button);
		mClearSearchWord = (ImageView)findViewById(R.id.clear_search_word);
		
		mSearchListView = (SearchListView)findViewById(R.id.search_listview);
		
		setSearchHistoryData();

		mInputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
		showSoftKeyBoard();
	}
	
	private void showSoftKeyBoard(){
		if (mInputMethodManager != null) {
			mInputMethodManager.showSoftInput(mNewsSearchEditText, 0);
        }
	}

	/**
	 * 设置搜索历史数据
	 */
	private void setSearchHistoryData() {
		List<String> list = FileUtils.readSearchHistoryData(SEARCH_HISTORY_FIlE_TAG);
		if(null != list && list.size() > 0){
			HistorySearchAdapter adapter = new HistorySearchAdapter(this, themeSettingsHelper, list);
			mSearchListView.setHistoryOrSuggestListViewAdapter(adapter);
		}
	}
	
	public void goBackClick(View view){
		finish();
	}
	
	public void clearSearchWord(View view){
		mNewsSearchEditText.setText("");
		showSoftKeyBoard();
	}
	
	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		// TODO Auto-generated method stub
		
		if(KeyEvent.KEYCODE_ENTER == event.getKeyCode()){
			mNewsSearchSubmit.performClick();
		} else if(KeyEvent.KEYCODE_BACK == event.getKeyCode()){
			finish();
		}
		
		return super.dispatchKeyEvent(event);
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		if(null != mSearchTask){
			mSearchTask.cancel(true);
			mSearchTask = null;
		}
	}
	
	private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            search_loadingbar.setVisibility(View.GONE);
        }
    };
	
	@Override
	public void onApplyTheme() {
		// TODO Auto-generated method stub
		super.onApplyTheme();
		
		themeSettingsHelper.setImageViewSrc(this, R.id.go_back_common_btn, R.drawable.go_back);
		themeSettingsHelper.setViewBackgroudColor(this, R.id.search_layout, R.color.main_bg_color);
		themeSettingsHelper.setViewBackgroud(this, R.id.top_banner, R.drawable.top_background);
		themeSettingsHelper.setImageViewSrc(this, R.id.top_id_image, R.drawable.netease_top);
		themeSettingsHelper.setTextViewColor(this, R.id.top_main_text, R.color.main_title_color);
		themeSettingsHelper.setViewBackgroud(this, R.id.search_submit_button, R.drawable.topcomment_column);
		themeSettingsHelper.setTextViewColor(this, R.id.search_submit_button, R.color.top_image_title_color);
	}
	
}
